package com.jcfk.system.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jcfk.common.core.exception.CustomException;
import com.jcfk.common.web.domain.*;
import com.jcfk.system.api.utils.LoginUserInfoUtils;
import com.jcfk.system.domain.dto.OaKeyworkTaskDTO;
import com.jcfk.system.domain.dto.SysOrganizationDTO;
import com.jcfk.system.domain.po.OaKeyworkInfo;
import com.jcfk.system.domain.po.OaKeyworkTask;
import com.jcfk.system.domain.po.SysOrganization;
import com.jcfk.system.domain.query.OaKeyworkInfoQuery;
import com.jcfk.system.domain.dto.OaKeyworkInfoDTO;
import com.jcfk.system.dao.OaKeyworkInfoDao;
import com.jcfk.common.business.service.BaseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import java.util.*;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.stream.Collectors;

/**
 * 重点工作
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-03-25
 */
@Service
public class OaKeyworkInfoService extends BaseService<OaKeyworkInfoDao, OaKeyworkInfo> {

    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private OaKeyworkTaskService oaKeyworkTaskService;


    /**
     * OaKeyworkInfo分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public RetPage<OaKeyworkInfoDTO> queryByPage(DataPage<OaKeyworkInfoDTO> page, OaKeyworkInfoQuery query) {
        // 用户信息
        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();

        QueryWrapper<OaKeyworkTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("keywork_id").eq("deleted", 0).and(wapper -> wapper.eq("leader_id", SecurityUtils.getUserId()).or().eq("created_user_id", SecurityUtils.getUserId()));
        queryWrapper.groupBy("keywork_id");
        List<Map<String, Object>> maps = oaKeyworkTaskService.listMaps(queryWrapper);

        // 外部权限
        List<String> ids = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            ids.add(map.get("keywork_id").toString());
        }
        query.setIds(ids);
        query.setCreatedUserId(SecurityUtils.getUserId());

        // 查询
        ReqPageParam<OaKeyworkInfo> requestParam = new ReqPageParam<>();
        requestParam.setCurrent(Integer.valueOf(String.valueOf(page.getCurrent())));
        requestParam.setSize(Integer.valueOf(String.valueOf(page.getSize())));

        QueryWrapper<OaKeyworkInfo> oaKeyworkInfoQueryWrapper = new QueryWrapper();
        oaKeyworkInfoQueryWrapper.lambda().eq(query.getWorkYear() != null, OaKeyworkInfo::getWorkYear, query.getWorkYear());
        // 查询条件
        oaKeyworkInfoQueryWrapper.lambda().like(!StringUtils.isEmpty(query.getWorkName()), OaKeyworkInfo::getWorkName, query.getWorkName());
        oaKeyworkInfoQueryWrapper.lambda().eq(!StringUtils.isEmpty(query.getWorkStatus()), OaKeyworkInfo::getWorkStatus, query.getWorkStatus());
        oaKeyworkInfoQueryWrapper.lambda().eq(!StringUtils.isEmpty(query.getOrganizationId()), OaKeyworkInfo::getOrganizationId, query.getOrganizationId());
        oaKeyworkInfoQueryWrapper.lambda().eq(OaKeyworkInfo::getDeleted, 0);

        if (query.getType() == null || "".equals(query.getType())) {
            // 超级管理员
            if (!"superadmin".equals(loginInfo.getUserType())) {
                oaKeyworkInfoQueryWrapper.lambda().and(wapper -> wapper.eq(OaKeyworkInfo::getCreatedUserId, SecurityUtils.getUserId()).or().in(ids.size() > 0, OaKeyworkInfo::getId, ids));
            }
        }

        oaKeyworkInfoQueryWrapper.orderByDesc("create_time");

        IPage<OaKeyworkInfo> retPage = this.getPageData(requestParam, oaKeyworkInfoQueryWrapper);
        Map<String, String> oamap = new HashMap<>();

        List<String> orgids = retPage.getRecords().stream().map(OaKeyworkInfo::getOrganizationId).collect(Collectors.toList());
        if (orgids.size() > 0) {
            QueryWrapper<SysOrganization> organizationQueryWrapper = new QueryWrapper<>();
            organizationQueryWrapper.lambda().in(SysOrganization::getId, orgids);
            List<SysOrganization> organizations = sysOrganizationService.list(organizationQueryWrapper);

            for (SysOrganization organization : organizations) {
                oamap.put(organization.getId(), organization.getOrganizationName());
            }
        }
        List<OaKeyworkInfoDTO> oaKeyworkInfoDTOS = convertList(retPage.getRecords(), OaKeyworkInfoDTO.class);
        for (OaKeyworkInfoDTO oaKeyworkInfoDTO : oaKeyworkInfoDTOS) {
            oaKeyworkInfoDTO.setOrganizationName(oamap.get(oaKeyworkInfoDTO.getOrganizationId()));
        }


        return new RetPage(oaKeyworkInfoDTOS, retPage.getTotal(), Long.valueOf(page.getSize()).intValue(), Long.valueOf(page.getCurrent()).intValue());

    }


    /**
     * OaKeyworkInfo分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public RetPage<OaKeyworkInfoDTO> performance(DataPage<OaKeyworkInfoDTO> page, OaKeyworkInfoQuery query) {
        // 用户信息
        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();

        QueryWrapper<OaKeyworkTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("keywork_id").eq("deleted", 0).and(wapper -> wapper.eq("leader_id", SecurityUtils.getUserId()).or().eq("created_user_id", SecurityUtils.getUserId()));
        queryWrapper.groupBy("keywork_id");
        List<Map<String, Object>> maps = oaKeyworkTaskService.listMaps(queryWrapper);

        // 外部权限
        List<String> ids = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            ids.add(map.get("keywork_id").toString());
        }
        query.setIds(ids);
        query.setCreatedUserId(SecurityUtils.getUserId());

        // 查询
        ReqPageParam<OaKeyworkInfo> requestParam = new ReqPageParam<>();
        requestParam.setCurrent(Integer.valueOf(String.valueOf(page.getCurrent())));
        requestParam.setSize(Integer.valueOf(String.valueOf(page.getSize())));

        QueryWrapper<OaKeyworkInfo> oaKeyworkInfoQueryWrapper = new QueryWrapper();
        oaKeyworkInfoQueryWrapper.lambda().eq(query.getWorkYear() != null, OaKeyworkInfo::getWorkYear, query.getWorkYear());
        // 查询条件
        oaKeyworkInfoQueryWrapper.lambda().like(!StringUtils.isEmpty(query.getWorkName()), OaKeyworkInfo::getWorkName, query.getWorkName());
        oaKeyworkInfoQueryWrapper.lambda().eq(!StringUtils.isEmpty(query.getWorkStatus()), OaKeyworkInfo::getWorkStatus, query.getWorkStatus());
        oaKeyworkInfoQueryWrapper.lambda().eq(!StringUtils.isEmpty(query.getOrganizationId()), OaKeyworkInfo::getOrganizationId, query.getOrganizationId());
        oaKeyworkInfoQueryWrapper.lambda().gt(OaKeyworkInfo::getWorkStatus, 0);
        oaKeyworkInfoQueryWrapper.lambda().eq(OaKeyworkInfo::getDeleted, 0);
        // 超级管理员
        if (!"superadmin".equals(loginInfo.getUserType())) {
            oaKeyworkInfoQueryWrapper.lambda().and(wapper -> wapper.eq(OaKeyworkInfo::getCreatedUserId, SecurityUtils.getUserId()).or().in(ids.size() > 0, OaKeyworkInfo::getId, ids));
        }
        oaKeyworkInfoQueryWrapper.orderByDesc("create_time");

        IPage<OaKeyworkInfo> retPage = this.getPageData(requestParam, oaKeyworkInfoQueryWrapper);
        Map<String, String> oamap = new HashMap<>();

        List<String> orgids = retPage.getRecords().stream().map(OaKeyworkInfo::getOrganizationId).collect(Collectors.toList());
        if (orgids.size() > 0) {
            QueryWrapper<SysOrganization> organizationQueryWrapper = new QueryWrapper<>();
            organizationQueryWrapper.lambda().in(SysOrganization::getId, orgids);
            List<SysOrganization> organizations = sysOrganizationService.list(organizationQueryWrapper);

            for (SysOrganization organization : organizations) {
                oamap.put(organization.getId(), organization.getOrganizationName());
            }
        }
        List<OaKeyworkInfoDTO> oaKeyworkInfoDTOS = convertList(retPage.getRecords(), OaKeyworkInfoDTO.class);
        for (OaKeyworkInfoDTO oaKeyworkInfoDTO : oaKeyworkInfoDTOS) {
            oaKeyworkInfoDTO.setOrganizationName(oamap.get(oaKeyworkInfoDTO.getOrganizationId()));
        }


        return new RetPage(oaKeyworkInfoDTOS, retPage.getTotal(), Long.valueOf(page.getSize()).intValue(), Long.valueOf(page.getCurrent()).intValue());

    }


    /**
     * 判断OaKeyworkInfo是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(OaKeyworkInfoDTO dto) {
        QueryWrapper<OaKeyworkInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入重点工作
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(OaKeyworkInfoDTO dto) {

        // 保存
        OaKeyworkInfo item = new OaKeyworkInfo();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);
    }

    /**
     * 更新重点工作
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(OaKeyworkInfoDTO dto) {

        // 保存
        OaKeyworkInfo item = new OaKeyworkInfo();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }

    /**
     * 根据批量主键删除重点工作(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(OaKeyworkInfoDTO dto) {

        OaKeyworkInfo item = new OaKeyworkInfo();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<OaKeyworkInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        QueryWrapper<OaKeyworkTask> oaKeyworkTaskQueryWrapper = new QueryWrapper<>();
        oaKeyworkTaskQueryWrapper.lambda().in(OaKeyworkTask::getKeyworkId, dto.getIds());
        oaKeyworkTaskQueryWrapper.lambda().in(OaKeyworkTask::getDeleted, 0);

        long count = oaKeyworkTaskService.count(oaKeyworkTaskQueryWrapper);

        if (count > 0) {
            throw new CustomException("该工作不能直接删除，请先删除工作中的子任务！");
        }


        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(OaKeyworkInfo item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
        item.setDeleted(0);
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }

    /**
     * 根据主键获取重点工作信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public OaKeyworkInfoDTO get(String id) {
        // 查询数据
        OaKeyworkInfo item = this.baseMapper.selectById(id);
        OaKeyworkInfoDTO dto = new OaKeyworkInfoDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }
        SysOrganizationDTO sysOrganization = sysOrganizationService.get(item.getOrganizationId());
        if (sysOrganization != null) dto.setOrganizationName(sysOrganization.getOrganizationName());

        return dto;
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<OaKeyworkInfoDTO>
     */
    public List<OaKeyworkInfoDTO> getList(OaKeyworkInfoQuery query) {
        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();

        // 查询条件
        QueryWrapper<OaKeyworkInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(query.getWorkYear() != null, OaKeyworkInfo::getWorkYear, query.getWorkYear());
        qw.lambda().ge(!StrUtil.isEmpty(query.getStartDateStart()), OaKeyworkInfo::getStartDate, query.getStartDateStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getStartDateEnd()), OaKeyworkInfo::getStartDate, query.getStartDateEnd());
        qw.lambda().ge(!StrUtil.isEmpty(query.getEndDateStart()), OaKeyworkInfo::getEndDate, query.getEndDateStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getEndDateEnd()), OaKeyworkInfo::getEndDate, query.getEndDateEnd());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getWorkName()), OaKeyworkInfo::getWorkName, query.getWorkName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getWorkStatus()), OaKeyworkInfo::getWorkStatus, query.getWorkStatus());
        qw.lambda().eq(!StrUtil.isEmpty(query.getOrganizationId()), OaKeyworkInfo::getOrganizationId, query.getOrganizationId());
        qw.lambda().eq(OaKeyworkInfo::getDeleted, 0);
        // 超级管理员
        if (!"superadmin".equals(loginInfo.getUserType())) {

            QueryWrapper<OaKeyworkTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("keywork_id").eq("deleted", 0).and(wapper -> wapper.eq("leader_id", SecurityUtils.getUserId()).or().eq("created_user_id", SecurityUtils.getUserId()));
            queryWrapper.groupBy("keywork_id");
            List<Map<String, Object>> maps = oaKeyworkTaskService.listMaps(queryWrapper);

            // 外部权限
            List<String> ids = new ArrayList<>();
            for (Map<String, Object> map : maps) {
                ids.add(map.get("keywork_id").toString());
            }

            qw.lambda().and(wapper -> wapper.eq(OaKeyworkInfo::getCreatedUserId, SecurityUtils.getUserId()).or().in(ids.size() > 0, OaKeyworkInfo::getId, ids));
        }

        qw.orderByDesc("create_time");

        // 查询数据
        List<OaKeyworkInfo> list = super.list(qw);


        return convertList(list, OaKeyworkInfoDTO.class);
    }
}

